# coding=utf-8
from flask import Flask, session
from flask import current_app, jsonify, request, g
from iHome import constants, db
from iHome.response_code import RET
from iHome.utils.image_store import image_store
from . import api
from iHome.models import User
from iHome.utils.commons import login_required


@api.route('/user/auth')
@login_required
def get_user_auth():
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户信息失败')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')
    return jsonify(errno=RET.OK, errmsg='', data=user.auth_to_dict())


# 用户实名认证逻辑
@api.route('/user/auth', methods=['POST'])
@login_required
def set_user__auth():
    req_dict = request.json
    real_name = req_dict.get('real_name')
    id_card = req_dict.get('id_card')
    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户信息失败')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')
    if user.real_name and user.id_card:
        return jsonify(errno=RET.DATAEXIST, errmsg='用户已经实名认证')
    user.real_name = real_name
    user.id_card = id_card
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='实名认证失败')

    return jsonify(errno=RET.OK, errmsg='实名认证成功')


@api.route('/user/name', methods=['PUT'])
@login_required
def set_user_name():
    req_dict = request.json
    username = req_dict.get('username')
    # user_id = session.get('user_id')
    user_id = g.user_id
    if not username:
        return jsonify(errno=RET.PARAMERR, errmsg='请输入昵称')
    try:
        user = User.query.filter(User.name == username, User.id != user_id).first()
    except Exception as e:
        user = None
        current_app.logger.error(e)
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='用户名已经存在')

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户失败')
    if not user:
        return jsonify(errno=RET.DATAEXIST, errmsg='用户不存在')

    user.name = username
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='设置用户名失败')
    return jsonify(errno=RET.OK, errmsg='设置用户名成功')


@api.route('/user/avatar', methods=['POST'])
@login_required
def set_user_avatar():
    file = request.files.get('avatar')
    if not file:
        return jsonify(errno=RET.PARAMERR, errmsg='请选择图片')
    try:
        key = image_store(file.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传头像失败')
    # 设置用户的头像记录
    # user_id = session.get('user_id')
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户信息失败')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')
    user.avatar_url = key
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='头像保存失败')
    # 返回应答
    avatar_url = constants.QINIU_DOMIN_PREFIX + key
    return jsonify(errno=RET.OK, errmsg='上传头像成功', data={'avatar_url': avatar_url})


@api.route('/user')
@login_required
def get_user_info():
    # 获取当前用户的登录ID
    user_id = g.user_id
    # 2. 根据id获取用户的信息（如果查不到，说明用户不存在)
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户信息失败')
    if not user:
        return jsonify(errno=RET.DATAERR, errmsg='用户不存在')
    # 返回应答
    # resp = {
    #     'user_id': user.id,
    #     'username': user.name,
    #     'avatar_url': constants.QINIU_DOMIN_PREFIX + (user.avatar_url if user.avatar_url else '')
    #
    # }
    return jsonify(errno=RET.OK, errmsg='OK', data=user.to_dict())
